package com.atguigu.wordcount.outputformat;

import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * @ClassName MyRecordWriter
 * @DeScription MyRecordWriter
 * @Author 剧情再美终是戏
 * @Date 2019/11/19 18:39
 * @Version 1.0
 **/
public class MyRecordWriter extends RecordWriter<String, NullWritable> {

    private String atguiguPath;
    private String otherPath;
    private FSDataOutputStream atguiguOs;
    private FSDataOutputStream otherOs;
    private FileSystem fs;


    public MyRecordWriter(TaskAttemptContext context) throws IOException {
        atguiguPath = "E:/atguigu.txt";
        otherPath = "E:/other.txt";
        fs = FileSystem.get(context.getConfiguration());
        if (fs != null) {
            atguiguOs = fs.create(new Path(atguiguPath));
            otherOs = fs.create(new Path(otherPath));
        }
    }

    public void write(String key, NullWritable value) throws IOException, InterruptedException {
        if (key.contains("atguigu")) {
            atguiguOs.write(key.getBytes());
        } else {
            otherOs.write(key.getBytes());
        }
    }

    public void close(TaskAttemptContext context) throws IOException, InterruptedException {
        if (null != atguiguOs) {
            IOUtils.closeStream(atguiguOs);
        }

        if (null != otherOs) {
            IOUtils.closeStream(otherOs);
        }
        if (fs != null) {
            fs.close();
        }
    }

}
